package com.example.park

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.example.base.entity.ParkEntityItem
import com.example.base.net.ApiService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withContext

class ParkDataSource(val apiService: ApiService,val spaceType:String):PagingSource<Int,ParkEntityItem>() {
    override fun getRefreshKey(state: PagingState<Int, ParkEntityItem>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, ParkEntityItem> {
       return withContext(Dispatchers.IO){
           try {
               val res = apiService.parkType(spaceType).first()
               if(res.code==200){
                   LoadResult.Page(res.data,null,null)
               }else{
                   LoadResult.Error(Exception(res.message))
               }
           }catch (e:Exception){
               LoadResult.Error(Exception(e))
           }
       }
    }
}